import { MAP_CONFIG } from './config.js'

function addLine(lineArr, layer) {
  //lineArr存放线要素的数组[[x1,y1],[x2,y2],...]
  const pointArr = lineArr.map(
    (point) => new Zondy.Object.Point2D(point[0], point[1])
  )
  //构成折线的弧段
  const gArc = new Zondy.Object.Arc(pointArr)
  //构成线的折线
  const gAnyLine = new Zondy.Object.AnyLine([gArc])
  //设置线要素的几何信息
  const gline = new Zondy.Object.GLine(gAnyLine)
  //设置要素的几何信息
  const fGeom = new Zondy.Object.FeatureGeometry({ LinGeom: [gline] })
  //设置添加线要素的图形参数信息
  const clineInfo = new Zondy.Object.CLineInfo(MAP_CONFIG.lineStyle)
  //设置要素的图形参数信息
  const graphicInfo = new Zondy.Object.WebGraphicsInfo({
    InfoType: 2,
    LinInfo: clineInfo,
  })
  //设置添加线要素的属性信息，根据地图文档图形属性设置
  const attValue = ['武汉到北京的线']
  //创建一个线要素
  const newFeature = new Zondy.Object.Feature({
    fGeom: fGeom,
    GraphicInfo: graphicInfo,
    AttValue: attValue,
  })
  //设置要素为线要素
  newFeature.setFType(2)
  //创建一个要素数据集，根据地图文档图形属性设置
  const featureSet = new Zondy.Object.FeatureSet()
  const fldNumber = 1
  const fldName = ['name']
  const fldType = ['string']
  //创建属性结构设置对象
  const cAttStruct = new Zondy.Object.CAttStruct({
    FldName: fldName,
    FldNumber: fldNumber,
    FldType: fldType,
  })
  //设置要素数据集的树形结构
  featureSet.AttStruct = cAttStruct
  //将添加的线要素添加到属性数据集中
  featureSet.addFeature(newFeature)
  //创建一个地图编辑对象
  const editDocFeature = new Zondy.Service.EditDocFeature(
    MAP_CONFIG.docName,
    MAP_CONFIG.lineLayerIndex,
    {
      ip: MAP_CONFIG.ip,
      port: MAP_CONFIG.port,
    }
  )
  editDocFeature.add(featureSet, (data) => {
    onAddLineSuccess(data, layer)
  })
}

function onAddLineSuccess(data, layer) {
  if (data.succeed) {
    alert('添加成功')
    layer.refresh()
  } else {
    alert('添加失败')
  }
}

export default addLine
